    using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.ProcessManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ProcessManagements;

namespace RBAC.Read.Api.Application.Handler.ProcessManagements
{
    /// <summary>
    /// 工序分类分页列表 查询处理器（读）
    /// </summary>
    public class GetProcessClassificationsPageHandler : IRequestHandler<GetProcessClassificationsPageCommand, APIPaging<ProcessClassification>>
    {
        private readonly IBaseRepository<ProcessClassification> _repo;
        private readonly ILogger<GetProcessClassificationsPageHandler> _logger;

        public GetProcessClassificationsPageHandler(
            IBaseRepository<ProcessClassification> repo,
            ILogger<GetProcessClassificationsPageHandler> logger)
        {
            _repo = repo;
            _logger = logger;
        }

        public Task<APIPaging<ProcessClassification>> Handle(GetProcessClassificationsPageCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<ProcessClassification>();
            try
            {
                _logger.LogInformation("开始获取工序分类分页列表 PageIndex={PageIndex}, PageSize={PageSize}, Keyword={Keyword}, Status={Status}",
                    request.PageIndex, request.PageSize, request.Keyword, request.Status);

                var (where, parameters) = BuildWhereAndParams(request);
                var (data, total) = _repo.GetPaged(request.PageIndex, request.PageSize, where, request.OrderBy, parameters);

                result.Code = APIEnums.Success;
                result.PageDatas = data?.ToList() ?? new List<ProcessClassification>();
                result.TotalCount = total;
                result.Msg = "获取工序分类列表成功";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工序分类分页列表失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取工序分类列表失败";
                result.PageDatas = new List<ProcessClassification>();
                result.TotalCount = 0;
            }

            return Task.FromResult(result);
        }

        private (string where, object parameters) BuildWhereAndParams(GetProcessClassificationsPageCommand request)
        {
            var conditions = new List<string>();
            var p = new Dictionary<string, object>();

            if (!string.IsNullOrWhiteSpace(request.Keyword))
            {
                conditions.Add("(ClassificationCode LIKE @kw OR ClassificationName LIKE @kw)");
                p["kw"] = $"%{request.Keyword}%";
            }
            if (request.Status.HasValue)
            {
                conditions.Add("Status = @Status");
                p["Status"] = request.Status.Value;
            }

            var where = conditions.Count > 0 ? string.Join(" AND ", conditions) : string.Empty;
            return (where, p);
        }
    }
}
